﻿using Microsoft.Extensions.Options;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.MultiTenancy;

namespace Xms.Abp.MultiTenancy;

[Dependency(TryRegister = true)]
public class DefaultMultiTenantStore : IMultiTenantStore, ITransientDependency
{
    private readonly XmsDefaultTenantStoreOptions _options;
    public DefaultMultiTenantStore(IOptionsMonitor<XmsDefaultTenantStoreOptions> options)
    {
        _options = options.CurrentValue;
    }

    public TenantData Find(string name)
    {
        return _options.Tenants?.FirstOrDefault(t => t.Name == name);
    }

    public TenantData Find(Guid id)
    {
        return _options.Tenants?.FirstOrDefault(t => t.Id == id);
    }

    public Task<TenantData> FindAsync(string name)
    {
        return Task.FromResult(Find(name));
    }

    public Task<TenantData> FindAsync(Guid id)
    {
        return Task.FromResult(Find(id));
    }

    public TenantData[] GetAll()
    {
        return _options.Tenants;
    }

    public async Task<TenantData[]> GetAllAsync()
    {
        return await Task.FromResult(_options.Tenants);
    }

    TenantConfiguration ITenantStore.Find(string name)
    {
        return Find(name);
    }

    TenantConfiguration ITenantStore.Find(Guid id)
    {
        return Find(id);
    }

    async Task<TenantConfiguration> ITenantStore.FindAsync(string name)
    {
        return await Task.FromResult(Find(name));
    }

    async Task<TenantConfiguration> ITenantStore.FindAsync(Guid id)
    {
        return await Task.FromResult(Find(id));
    }
}
